function handleAjaxResponse(data) {
    // Show flash message if given in the Ajax response
    if (data.notice) {
        flash.notice(data.notice);
    }

    // Update the number of items in cart to the Cart link in navigation bar.
    if (data.numCartItems !== undefined) {
        if (data.numCartItems > 0) {
            $('#cart-contents').text("(" + data.numCartItems + ")");
        } else {
            $('#cart-contents').text('');
        }
    }

    // Replace parts of the page with the HTML given in the Ajax response.
    if (data.replace) {
        $.each(data.replace, function (id, html) {
            $('#' + id).html(html);
        });
    }
}

/**
 * Makes all cart related actions use Ajax.
 */
function ajaxifyCart() {
    var $productUpdateForm = $('form.product-quantity-form');

    // Submit "Add to cart", "Remove product from cart, "Update product
    // quantity" and "Clear cart" forms using AJAX.
    $('form.buy, ' +
      'form.product-remove-form, ' +
      'form.product-quantity-form, ' +
      'form.clear-cart-form').live('submit', function (event) {
        var $form = $(this),
            url = $form.attr('action'),
            data = $form.serialize();
        event.preventDefault();
        $.post(url, data, handleAjaxResponse);
    });

    // Update the cart automatically when product quantity is changed.
    $productUpdateForm.find(':text').live('change', function () {
        $(this).submit();
    });
}

$(document).ready(function () {
    ajaxifyCart();
});
